package com.me.mygdxgame.renderer;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.GLCommon;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Matrix4;
import com.me.mygdxgame.gamelogic.GameLogic;

public class RendererGL20 implements Renderer
{
	// batch to draw text
	private SpriteBatch spriteBatch;

	private Texture bgTexture;

	private BitmapFont font;

	private String status = "";

	private final Matrix4 viewMatrix = new Matrix4();
	private final Matrix4 transformMatrix = new Matrix4();

	private int num = 0;

	public RendererGL20()
	{
		try
		{
			spriteBatch = new SpriteBatch();
			
			bgTexture = new Texture(Gdx.files.internal("data/planet.jpg"),
					Format.RGB565, true);
			bgTexture.setFilter(TextureFilter.MipMap, TextureFilter.Linear);

			font = new BitmapFont(Gdx.files.internal("data/font16.fnt"),
					Gdx.files.internal("data/font16.png"), false);

		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	@Override
	public void render(GameLogic logic, float dt)
	{
		num = Gdx.graphics.getFramesPerSecond();
		GLCommon gl = Gdx.gl;
		gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);

		renderBG();

		gl.glEnable(GL20.GL_DEPTH_TEST);
		gl.glEnable(GL20.GL_CULL_FACE);
		
		Camera.getInstance().getCamera().update(true);

		ContextManager.getInstance().render(dt);
		
		gl.glDisable(GL20.GL_DEPTH_TEST);
		gl.glDisable(GL20.GL_CULL_FACE);
		
		
		spriteBatch.setProjectionMatrix(viewMatrix);
		spriteBatch.setTransformMatrix(transformMatrix);
		
		spriteBatch.begin();

		status = "FPS: " + num;

		spriteBatch.enableBlending();
		spriteBatch.setBlendFunction(GL20.GL_ONE, GL20.GL_ONE_MINUS_SRC_ALPHA);
		font.draw(spriteBatch, status, 0, 320);
		spriteBatch.end();

	}

	@Override
	public void dispose()
	{
		spriteBatch.dispose();
		bgTexture.dispose();
		font.dispose();

	}

	private void renderBG()
	{
		viewMatrix.setToOrtho2D(0, 0, 400, 320);
		spriteBatch.setProjectionMatrix(viewMatrix);
		spriteBatch.setTransformMatrix(transformMatrix);
		spriteBatch.begin();
		spriteBatch.disableBlending();
		spriteBatch.setColor(1,1,1,1);
		spriteBatch.draw(bgTexture, 0, 0, 480, 320, 0, 0, 512, 512, false,
				false);
		spriteBatch.end();
	}

}
